package com.eastchina.fids2focs.common.interceptor;

import java.text.MessageFormat;

import javax.servlet.http.HttpSession;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.xfire.transport.http.XFireServletController;

import com.eastchina.fids2focs.common.GlobalConstants;
import com.eastchina.fids2focs.common.exception.FIDSIIValidateException;
import com.eastchina.fids2focs.domain.SystemUser;

/**
 * Fids2异常处理拦截器
 * @author xiayg
 *
 */
public class FIDSIIExceptionInterceptor implements MethodInterceptor {
    /**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 738414089087306512L;

	/**
	 * 日志对象
	 */
	private static final Log log = LogFactory.getLog(FIDSIIExceptionInterceptor.class);
    
	/**
	 * 日志出力形式
	 */
    protected static final MessageFormat format = new MessageFormat("Sessionid:{0} Username:{1} Service:{2} (method:{3}) Error:[{4}]");
    
    /**
     * 异常信息出力
     */
	public Object invoke(MethodInvocation invoker) throws Throwable {
		try {
			return invoker.proceed();
		} catch (FIDSIIValidateException ex) {
			throw ex;
		} catch (Throwable th) {
			output(invoker, th);
			throw th;
		}
	}
	
	// 异常信息出力
	public void output(MethodInvocation invoker, Throwable th) {
		// 获取登录用户信息
		HttpSession session = XFireServletController.getRequest().getSession();
		SystemUser userObject = (SystemUser) session.getAttribute(GlobalConstants.USER_KEY);
		
		log.error(format.format(new Object[]{
				session.getId(),
				userObject == null ? null : userObject.getLoginId(),
				invoker.getThis().getClass().getSimpleName(),
				invoker.getMethod().getName(),
				ExceptionUtils.getFullStackTrace(th)
		}));
	}
}
